/**
 * 批量插图插件
 */
(function(E) {
var Consts = E.consts, 
	MultiImage = "MultiImage",
	//flash预览按钮id
	select_btn_id = 'select_file_btn',
	//一次最多上传图片张数
	file_queue_limit = 20,
	//每张图片最大值
	file_size_limit ="1MB";

E.plugin(MultiImage, {
	config : {
		width : 660,
		height : 350,
		position: 'center',
		overlay: true,
		maxWidth: 620
	},

	style : '.jqe-plugin-multiImage .header{color:#919191;height:30px;line-height:28px;position:relative;}\
			.jqe-plugin-multiImage .upload_btn{width:82px;height:26px;position:absolute;right:0;top:0;}\
			.jqe-plugin-multiImage .upload_msg{background-color:#F8F8F8;border:1px solid #ECECEC;height:26px;line-height:26px;margin-top:-1px;padding:0 12px;}\
			.jqe-plugin-multiImage .upload_msg span{color:#919191;float:left;}\
			.jqe-plugin-multiImage span.error_msg{color:red;margin-left:10px;}\
			.jqe-plugin-multiImage .upload_msg a{float:right;}\
			.jqe-plugin-multiImage .upload_msg a{text-decoration:none;color:#4B4B4B;}\
			.jqe-plugin-multiImage .upload_msg a:hover{text-decoration:underline;color:red;}\
			.jqe-plugin-multiImage .xuhao{width:43px;text-align:center;float:left;}\
			.jqe-plugin-multiImage .name{width:174px;padding-left:17px;float:left;}\
			.jqe-plugin-multiImage .size{width:103px;padding-left:36px;float:left;}\
			.jqe-plugin-multiImage .status{width:170px;padding-left:26px;float:left;}\
			.jqe-plugin-multiImage .delete{width:37px;text-align:center;float:left;}\
			.jqe-plugin-multiImage .blank{color:#000;}\
			.jqe-plugin-multiImage .delete img{width:9px;height:9px;margin:8px auto 0;cursor:pointer;}\
			.jqe-plugin-multiImage .upload_list{height:250px;overflow-y:scroll;border-width:0 1px;border-color:#ECECEC;border-style:solid;}\
			.jqe-plugin-multiImage .upload_list li{border-bottom:1px solid #ECECEC;clear:both;height:26px;line-height:26px;overflow:hidden;width:620px;}\
			.jqe-plugin-multiImage .upload_body_top{background-color:#F8F8F8;border:1px solid #ECECEC;height:26px;}\
			.jqe-plugin-multiImage .body li{color:#919191;height:26px;line-height:26px;padding:0;float:left;width:100%;}\
			.jqe-plugin-multiImage li,.jqe-plugin-multiImage p,.jqe-plugin-multiImage ul{list-style:none;padding:0;margin:0;overflow:hidden;}',
	init : function() {
		var html = '<div class="header">\
						支持jpg、jpeg、png、gif格式，单张图片不能超过1MB <div class="upload_btn"><a id="'+select_btn_id+'" href="javascript:void(0);"></a></div>\
					</div>\
					<div class="body">\
						<ul class="upload_body_top">\
							<li>\
							<p class="xuhao">序号</p>\
							<p class="name">上传图片列表</p>\
							<p class="size">大小</p>\
							<p class="status">状态</p>\
							<p class="delete">删除</p>\
							</li>\
						</ul>\
						<ul name="table_list" class="upload_list"></ul>\
						<div class="upload_msg">\
						<span name="file_size">共0张图片，0KB</span>\
						<span name="error_msg" class="error_msg"></span>\
						<a name="remove_all_file" href="javascript:void(0);">清空列表</a>\
						</div>\
					</div>\
					<div class="footer">\
						<label><input type="checkbox" name="user_file_name"> 以文件名为默认图片描述</label>\
					</div>';
		this.cache['html'] = '<div class="jqe-plugin-multiImage">' + html + "</div>";
	},
	ok : function( panel, self ) {
		upload_util.start(panel, self);
	},
	one : function(panel, self) {
		$.extend(true, upload_util, self._upload_util);
		upload_util.init(); 
	},
	get : function(panel, self) {
		var html = '';
		return html;
	},
	action : function( target, panel, self ) {
		var fun = target.attr("name");
		if(typeof Functions[fun] === Consts.typeof_function){
			return Functions[fun](target, panel, self);
		}
	},
	onclose : function(){
		var plugin = E.plugin(MultiImage),
			panel = plugin.panel,
			util = upload_util;
		panel.find("[name=remove_all_file]").click();
		util.parms.file_size = 0;
		util.parms.file_num = 0;
	},
	//给外部配置flash相关参数的借口
	_flash_settings : {},
	//可以覆盖整个上传组件
	_upload_util : {}
});



/*
	插件panel上面所有vent处理函数
*/

var Functions = {
	//删除文件
	remove_file : function( target, panel, plugin ) {
		var util = upload_util,
			parms = util.parms,
			file_size_mod = parms.file_size_mod,
			//获取需要删除的tr
			remove_item = target.closest("li[file_id]").eq(0),
			//获取需要删除文件的id
			file_id = remove_item.attr("file_id"),
			//获取需要删除文件的大小
			file_size = remove_item.find("p[size]"),
			//获取原来存放总图片数量和图片大小的标签
			sizeObj = panel.find("[name=file_size]"),
			size = 0;
		file_size = parseFloat(file_size.attr("size"));
		parms.file_num -= 1;
		parms.file_num = parms.file_num < 0 ? 0 : parms.file_num;
		parms.file_size -= file_size;
		size = parms.file_size > 0 ? parms.file_size : 0;
		if(size <= 0) {
			size = '0KB';
		}else {
			size = size > 1024 * 1024 ? (size / (1024 * 1024)).toFixed(2) + "MB" : (size/1024).toFixed(2) + "KB";
		}
		sizeObj.text(file_size_mod.replace('[num]',parms.file_num).replace('[size]', size));
		remove_item.remove();
		//从flash删除文件
		util.swf_upload.cancelUpload(file_id,false);
		//更新页面上显示的索引值
		util._update_index();
		return false;
	},
	
	//清除所有
	remove_all_file : function( target, panel, plugin ) {
		var util = upload_util;
		if(util.parms.upload_busy)return alert("上传中...");
		var file_size_mod = util.parms.file_size_mod;
		panel.find("li[file_id]").each(function() {
			var obj = $(this);
			util.swf_upload.cancelUpload(obj.attr("file_id"), false);
			obj.remove();
		});
		util.parms.file_size = 0;
		util.parms.file_num = 0;
		//获取原来存放总图片数量和图片大小的标签
		var sizeObj = panel.find("[name=file_size]");
		sizeObj.text(file_size_mod.replace('[num]',0).replace('[size]','0KB'));
		panel.find("[name=error_msg]").text("");
		return false;
	}
}

/*
	插件依赖的上传组件
*/
var upload_util = {
	init : function() {
		var self = this,
			settings = self.flash_settings;
		settings['file_dialog_start_handler'] = self.fileDialogStart;
		settings['file_queued_handler'] = self.fileQueued;
		settings['file_queue_error_handler'] = self.fileQueueError;
		settings['file_dialog_complete_handler'] = self.fileDialogComplete;
		settings['upload_start_handler'] = self.uploadStart;
		settings['upload_success_handler'] = self.uploadSuccess;
		settings['upload_complete_handler'] = self.uploadComplete;
		$.extend(true,settings,E.plugin(MultiImage)._flash_settings);
		self.swf_upload = new SWFUpload(settings);
	},
	//上传组件
	swf_upload : null,
	//上传数据
	upload_data : [],
	//是否使用图片名称作为描述
	description : false,
	//上传过程提示语言
	
	// msg_array : {'0' : '上传失败!',
				// '1' : '上传成功',
				// '2' : '上传成功',
				// '3' : '对不起，您未登录，请登录后再上传',
				// '4' : '上传失败',
				// '5' : '图片超过1MB，已将跳过',
				// '6' : '图片数据不正常'},
	
	msg_array : {'0' : '上传的文件为空!',
				'1' : '上传的图片太大',
				'2' : '上传的图片类型不对',
				'3' : '对不起，您未登录，请登录后再上传',
				'4' : '上传失败',
				'5' : '上传失败',
				'6' : '图片被冻结',
				'7' : '程序异常',
				'ok': '上传成功'
	},
				
	//插件内部需要的一些参数
	parms : {
		//一张图片所在一行的tr模板
		upload_item : '<li file_id="[id]"><p class="xuhao">[index]</p><p class="name blank" title="[url]">[url]</p><p size="[size_value]" class="size blank">[size]</p><p status="1" class="status">待上传</p><p class="delete"><img class="" name="remove_file" src="http://www.huimg.cn/composition/images/dustbin100629.gif" title="点击删除图片" style=""></p></li>',
		//图片总数和总大小提示模板
		file_size_mod : '共[num]张图片，[size]',
		//图片总大小
		file_size : 0,
		//图片总数
		file_num : 0,
		//防止多次点击上传
		upload_busy : false
	},
	/*
		开始上传
	*/
	start : function(panel,plugin) {
		var self = this;
		if(self.swf_upload.getStats().files_queued == 0) {
			panel.find('[name=error_msg]').text('你还没有选择你要上传的文件!');
			return false;
		}
		if(self.parms.upload_busy) {
			return false;
		}
		panel.find('[name=error_msg]').text('正在上传...');
		self.parms.upload_busy = true;
		plugin.lock();
		panel.find("[name=remove_file]").hide();
			//图片处理接口必须参数：userIden
		var userIden = $('#curuser_iden').length?$('#curuser_iden').val():'', //QfnEAAAgEBmB8e3l0
			type = $('#type').val() == 19? 19: 14, //[14]主站文章=14，小百科19
			sourceId = $('#art_iden').length? $('#art_iden').val(): '',
			sourceTitle = $('#art_title').length? $('#art_title').val(): '',
			data = {'userIden': userIden, 'type': type, 'sourceId': sourceId, 'sourceTitle': sourceTitle, 'doc_title': sourceTitle},
			check_box = panel.find("[name=user_file_name]:checked");
		self.description = check_box.length? true: false;
		check_box.attr("disabled",true);
		//设置请求相关参数
		self.swf_upload.setPostParams(data);
		self.swf_upload.setButtonDisabled(true);
		self.swf_upload.startUpload();
	},
	
	//开始上传
	uploadStart : function(file) {
		var self = E.plugin(MultiImage),
			panel = self.panel,
			util = upload_util,
			fileDescription = util.description ? file.name.substring(0, file.name.lastIndexOf(".")) : "图片 "+(file.index+1);
		util.swf_upload.addFileParam(file.id, 'description', fileDescription); 
	},
	
	/*
	数据成功提交到服务端时触发的事件，此时并没完成一个上传周期
	file : 文件对象
	serverdata : 服务端返回的数据
	*/
	uploadSuccess : function(file, serverdata) {
		var self = E.plugin(MultiImage),
			panel = self.panel,
			util = upload_util,
			item = panel.find('[file_id='+file.id+']'),
			obj = null,
			msg_array = util.msg_array;
		if(serverdata==""||serverdata==undefined||serverdata==null) {
			item.find("[status]").text('上传失败!');
			return;
		}
		try {
			obj = JSON.parse(serverdata, function(key, value) {return value;});
		}catch(e) {
			item.find("[status]").text('上传失败!');
			return;
		}
		if(obj && obj.flag in msg_array) {
			item.find("[status]").text(msg_array[obj.flag]);
			if(obj.flag == 'ok') {
				var data = {};
				data.flag = obj.flag;
				data.url = obj.url;
				data.md5 = obj.md5;
				data.type = obj.type;
				data.length = obj.size;
				data.size = obj.width + "x" + obj.height;
				data.name = file.name;
				data.description = file.post.description;
				util.upload_data.push(data);
			}else if(obj.flag == '3') {
				alert(msg_array[obj.flag]);
				var date = new Date();
				date.setTime(date.getTime() + 24 * 3600 * 1000);
				document.cookie = 'nextURL=' + document.location.href + ';expire=' + date.toGMTString()+ ';path=/;domain=.baike.com;'
				window.location.href = "http://wiki.baike.com/user/login/userLogin.jsp";
			}
		}else {
			item.find("[status]").text("上传失败");
		}
	},
	
	/*
	一个上传周期完成后执行的方法，对于多文件上传时可以在此方法中调用 SWFUpload.startUpload()方法
	file : 文件对象
	*/
	uploadComplete : function(file) {
		var self = E.plugin(MultiImage),
			panel = self.panel,
			util = upload_util;
		util.swf_upload.cancelUpload(file.id, false);
		if(util.swf_upload.getStats().files_queued) {
			util.swf_upload.startUpload();
		}else {
			panel.find('[name=error_msg]').text("上传完毕！！！");
			util.swf_upload.setButtonDisabled(false);
			panel.find("[name=user_file_name]").attr("disabled",false);
			util.insert(self,util);
			util.parms.upload_busy = false;
			E.monitor(self.name);
			setTimeout(function(){
				var Resize = E.plugin("Resize");
				Resize && Resize.autoHeight();
			}, 2000);
			self.unlock();
			self.hide();
		}
	},
	//弹出选择file框
	fileDialogStart : function() {
		var util = upload_util;
		util.swf_upload.setButtonDisabled(true);
	},
	//选择完文件后触发
	fileDialogComplete : function() {
		var util = upload_util;
		util.swf_upload.setButtonDisabled(false);
	},
	
	/*
		确定选择文件时[选择几个文件就执行几次]
		file : 文件对象
	*/
	fileQueued : function(file) {
		var self = E.plugin(MultiImage),
			panel = self.panel,
			util = upload_util,
			parms = util.parms,
		//获取一张图所在行tr模板
			mod = util.parms.upload_item,
		//获取图片数量大小提示语模板
			file_size_mod = util.parms.file_size_mod,
		//将图片大小转为KB
			file_size = file.size,
		//获取显示图片张数和大小的标签
			sizeObj = panel.find("[name=file_size]"),
			index = 0,
			size = 0,
			file_size_str = null;
		parms.file_num += 1;
		index = parms.file_num > 9 ? parms.file_num : "0" + parms.file_num;
		parms.file_size = file_size + parms.file_size;
		size = parms.file_size >1024*1024 ? (parms.file_size / (1024 * 1024)).toFixed(2) + "MB" : (parms.file_size/1024).toFixed(2) + "KB";
		file_size_str = file_size > 1024*1024 ? (file_size / (1024 * 1024)).toFixed(2) + "MB" : (file_size/1024).toFixed(2) + "KB";
		//拼装模板
		mod = mod.replace(/\[id\]/g, file.id).replace('[index]', index).replace(/\[size_value\]/g, file_size).replace(/\[size\]/g,file_size_str).replace(/\[url\]/g, file.name);
		panel.find('[name=table_list]').append(mod);
		sizeObj.text(file_size_mod.replace('[num]', parms.file_num).replace('[size]', size));
	},
	
	/*
	单个文件错误处理方法[错误原因：超过了上传大小限制，文件为零字节，超过文件队列数量限制，设置之外的无效文件类型。]
	file : 文件对象与fileQueued参数说明一致
	error_code : 错误代码，对应SWFUpload对象中的UPLOAD_ERROR
	message : 错误信息
	*/
	fileQueueError : function( file, error_code, message ) {
		var self = E.plugin(MultiImage);
		var panel = self.panel;
		var error_msg = "";
		var error_array = {'-100' : "上传文件数量超过最大限制"+file_queue_limit+"个!",
						'-110' : "文件大小不能超过"+file_size_limit+"!",
						'-120' : "文件为零字节!",
						'-130' : "无效文件类型!"
						};
			if(error_code in error_array) {
				error_msg = error_array[error_code];
			}else if(typeof message =="string") {
				error_msg = message;
			}else {
				error_msg = "未知错误!";
			}
		if( file ) {
			panel.find('[name=error_msg]').text(file.name + ":" + error_msg );
		}else {
			panel.find('[name=error_msg]').text(error_msg);
		}
	},
	//更新所有上传文件第一列索引值
	_update_index : function() {
		var self = E.plugin(MultiImage);
		var panel = self.panel;
		panel.find('li[file_id]').each(function(i,item) {
			var ind = i+1; 
			ind = ind > 9 ? ind : "0" + ind;
			$(item).children("p:first").text(ind);
		});
	},
	//flash配置信息
	flash_settings : {
		flash_url : "http://tupian.baike.com/zutu/flash/swfupload.swf",
		upload_url : "http://a5.att.baike.com/uploadGroupImage.wiki",
		file_size_limit : file_size_limit,
		file_types : "*.jpg;*.png;*.gif;*.jpeg",
		file_types_description : "All Images",
		file_queue_limit : file_queue_limit,
		file_post_name : "photofile",
		custom_settings : {
			currentSize : 0,
			totalSize : 0,
			fileList: [],
			fileSizeList : [],
			progressList : [],
			totalProgressBar : [],
			cancelButton : "cancelButton",
			submitButton : "submitButton",
			deleteAllButton : "swf_delete_all",
			totalFiles : "swf_files",
			totalFileSize : "swf_size",
			progressName : "swfProgress",
			deleteName : "delete_name",
			listName : "listName",
			listHolder : "listHolder"
		},
		debug : false,
		button_window_mode : "opaque",
		button_image_url : "http://www.huimg.cn/HDeditor/essay-editor/skins/browse.gif",
		button_width : "82",
		button_height : "26",
		button_placeholder_id : select_btn_id,
		button_text : "",
		button_text_style : "",
		button_text_left_padding : 0,
		button_text_top_padding : 0,
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
		button_cursor : SWFUpload.CURSOR.HAND,
		button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT
	},
	/*
		插入内容
	*/
	insert : function(plugin, util) {
		var datalist = util.upload_data,
			html=[];
		for(var key in datalist){
			var data = datalist[key],
				title = data.description,
				img_src = util.getPicSRC(data.flag, data.url),
				img_link = util.getPicHTML(img_src),
				size = data.size.split('x'),
				maxWidth = plugin.config.maxWidth,
				realWidth = size[0],
				cssClass = '',
				cssStyle = '',
				htmlWidth = 0,
				widthHtml = '';
			img_src = img_src.replace(/\.(gif|jpg|png|jpeg)/i, '_950.$1');
			if(realWidth >= maxWidth) {
				htmlWidth = maxWidth;
				cssClass = "img_c";//"img_c_620";
				cssStyle = htmlWidth + "px;";
				widthHtml = ' width="' + htmlWidth + '" ';
			} else {
				htmlWidth = realWidth;
				cssClass = "img_c";
				cssStyle = htmlWidth + "px;";
			}
			html.push('<br /><br /><DIV class="img ' + cssClass + '" style="width:'+ cssStyle +'">');
			if (img_link) {
				html.push('<A title="' + title + '" href="' + img_link + '" target=_blank>');
			}
			html.push('<IMG title="'+title+'" alt="'+title+'" src="'+img_src+'" ' + widthHtml + ' />');
			if (img_link) {
				html.push('</A>');
			}
			html.push('<STRONG>'+title+'</STRONG></DIV><br />');
		}
		plugin.pasteHTML(html.join(''));
		//清空缓存记录 
		util.upload_data = [];
	},
	getPicSRC: function(flag, source) {
		var src = "";	
		if (flag == 'ok') {
			 src = source;
		 }
		return src;
	},
	getPicHTML : function(src) {
		var prefix = "http://tupian.baike.com/",
			url = "",
			pattern = /http:\/\/(a\d+)\.att.(?:hudong|baike).com\/(\d+)\/(\d+)\/([^.]+)\.(gif|jpg|png|jpeg)/i,
			parts = pattern.exec(src);
		if (parts != null && parts.length == 6) {
			url = prefix + parts[1] + "_" + parts[2] + "_" + parts[3] + "_" + parts[4] + "_" + parts[5] + ".html";
		} else {
			url = src;
		}
		return url;
	}
}
})(jQEditor);